﻿using Com.JunCaiSoft.API.Common.AssistClass;
using Com.JunCaiSoft.Common.Extension;
using Com.JunCaiSoft.WXWork.Model;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Com.JunCaiSoft.WXWork.Common
{
    /// <summary>
    /// 企业微信AccessToken获取帮助类
    /// </summary>
    public static class WXWorkAccessToken
    {
        /// <summary>
        /// AccessTokenURL
        /// </summary>
        private static String accesstokenURL;
        /// <summary>
        /// 企业微信企业标识
        /// </summary>
        private static String corpid;
        /// <summary>
        /// 获取AccessToken
        /// </summary>
        /// <param name="AccessTokenURL"></param>
        /// <param name="Corpid"></param>
        /// <param name="CorpSecret"></param>
        /// <returns></returns>
        public static AccessToken GetAccessToken(String AccessTokenURL, String Corpid,String CorpSecret)
        {
            try
            {
                corpid = Corpid;
                accesstokenURL = AccessTokenURL + "?corpid=" + Corpid + "&corpsecret=" + CorpSecret;
                var accessToken = JsonConvert.DeserializeObject<AccessToken>(HttpExtension.HttpGet(accesstokenURL, true, null, "application/json;"));
                if(accessToken.errcode == 0)
                {
                    return accessToken;
                }
                else
                {
                    throw new Exception(accessToken.errmsg);
                }
            }
            catch(Exception e)
            {
                throw e;
            }
        }
    }
}
